package com.ligongmusic.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.ligongmusic.R;
import com.ligongmusic.activity.MusicActivity;
import com.ligongmusic.adapter.UniversalAdapter;
import com.ligongmusic.adapter.ViewHolder;
import com.ligongmusic.base.BaseFragment;
import com.ligongmusic.domain.DynamicDomain;
import com.ligongmusic.util.GlobalParams;
import com.ligongmusic.util.JsonUtils;
import com.ligongmusic.util.LoggerUtils;
import com.ligongmusic.util.NetWorkUtils;
import com.ligongmusic.util.NetWorkUtils.NetWorkCallBack;
import com.ligongmusic.util.StringUtils;
import com.ligongmusic.view.XListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public class Ranking extends BaseFragment {
    private ViewPager mViewPager;
    private XListView mListView;
    private List<ImageView> pagerViews;
    private List<DynamicDomain> dynamics;
    private boolean isFirst = true;
    //	private int playingMusic = -1;
    public static DisplayImageOptions options2 = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.music_icon) //设置图片在下载期间显示的图片
            .showImageForEmptyUri(R.drawable.music_icon)//设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.drawable.music_icon)  //设置图片加载/解码过程中错误时候显示的图片
            .cacheInMemory(true)//设置下载的图片是否缓存在内存中
            .imageScaleType(ImageScaleType.IN_SAMPLE_INT)//设置图片以如何的编码方式显示
            .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型
            .build();//构建完成;

    @Override
    protected View layoutInflater(LayoutInflater inflater, ViewGroup container,
                                  Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ranking, null);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if(isVisibleToUser){
            if (isFirst || GlobalParams.isRefreshRanking) {
                GlobalParams.isRefreshRanking = false;
                getData();
            }
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(StringUtils.getTime(System.currentTimeMillis()));
    }

    private void onLoad(String message) {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(message);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void getData() {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("token", GlobalParams.token));
        pairs.add(new BasicNameValuePair("page", "0"));
        pairs.add(new BasicNameValuePair("size", "20"));
        pairs.add(new BasicNameValuePair("loginname", GlobalParams.userName));
        NetWorkUtils.getRequest(pairs, GlobalParams.DYNAMIC_LIST, new NetWorkCallBack() {
            @Override
            public void success(String result) {
                isFirst = false;
                onLoad();
//				LoggerUtils.getLog(Dynamic.class).error(result);
                Log.e("LoggerUtils", "Ranking:" + result);
                dynamics = JsonUtils.jsonToBeanList(result, DynamicDomain.class);
                if (dynamics == null)
                    return;
                mListView.setAdapter(new UniversalAdapter<DynamicDomain>(getActivity(), dynamics, R.layout.ranking_item) {
                    @Override
                    public void convert(ViewHolder holder, DynamicDomain t, int position) {
                        holder.setText(R.id.tv_music_name, t.getSong_name());
                        holder.setText(R.id.tv_singer, t.getMusician_name() + "");
//						holder.setText(R.id.tv_prise_num, "赞（" + t.getLike_count() + "）");
                        TextView prise = holder.getView(R.id.tv_prise_num);
                        prise.setText("赞（" + t.getLike_count() + "）");
                        ImageView image = holder.getView(R.id.music_icon);
                        TextView rankNum = holder.getView(R.id.tv_rank_num);
                        ImageLoader.getInstance().displayImage(GlobalParams.IMAGE_URL + t.getCover(), image, options2);
                        ImageView rank = holder.getView(R.id.iv_rank_num);
                        if (position == 0) {
                            holder.setImageResource(R.id.iv_rank_num, R.drawable.no_1);
                            rankNum.setVisibility(View.GONE);
                            rank.setVisibility(View.VISIBLE);
//							rank.setBackground(getResources().getDrawable(R.drawable.no_1));
                        } else if (position == 1) {
                            holder.setImageResource(R.id.iv_rank_num, R.drawable.no_2);
                            rankNum.setVisibility(View.GONE);
                            rank.setVisibility(View.VISIBLE);
//							rank.setBackground(getResources().getDrawable(R.drawable.no_2));
                        } else if (position == 2) {
                            holder.setImageResource(R.id.iv_rank_num, R.drawable.no_3);
                            rankNum.setVisibility(View.GONE);
                            rank.setVisibility(View.VISIBLE);
//							rank.setBackground(getResources().getDrawable(R.drawable.no_3));
                        } else {
                            rank.setVisibility(View.GONE);
                            rankNum.setVisibility(View.VISIBLE);
                            rankNum.setText((position + 1) + "");
                        }
                    }
                });
                mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        DynamicDomain t = dynamics.get(position - 1);
                        Intent intent = new Intent(getActivity(), MusicActivity.class);
                        if (GlobalParams.playing_song_id == -1) {//首次播放
                            //记录播放id
                            GlobalParams.playing_song_id = t.getSong_id();
                            intent.putExtra("player", MusicActivity.MUSIC_NEW);// 新音乐
                        } else {//非首次播放
                            if (GlobalParams.playing_song_id == t.getSong_id())
                                intent.putExtra("player", MusicActivity.MUSIC_CONTINUE);
                            else {
                                intent.putExtra("player", MusicActivity.MUSIC_NEW);// 新音乐
                                GlobalParams.playing_song_id = t.getSong_id();// 记录当前播放
                            }
                        }
                        intent.putExtra("info", t);
//						DynamicDomain t = dynamics.get(position);
                        getActivity().startActivity(intent);
                    }
                });
            }

            @Override
            public void error(String message) {
                isFirst = true;
                onLoad("加载失败");
                LoggerUtils.getLog(Dynamic.class).error(message);
            }

            @Override
            public void error() {
                onLoad("加载失败");
                isFirst = true;
            }
        });
    }

    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        pagerViews = new ArrayList<ImageView>();
        mViewPager = getView(R.id.ranking_vp);
        mListView = getView(R.id.ranking_list);
        mListView.setPullRefreshEnable(true);
        mListView.setPullLoadEnable(false);
        mListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                getData();
            }

            @Override
            public void onLoadMore() {
                // 无方法
            }
        });
        for (int i = 0; i < 3; i++) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setScaleType(ScaleType.FIT_XY);
            imageView.setBackgroundResource(R.drawable.banner);
            pagerViews.add(imageView);
        }
        mViewPager.setAdapter(new PagerAdapter() {
            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public int getCount() {
                return pagerViews.size();
            }

            //滑动切换的时候销毁当前的组件
            @Override
            public void destroyItem(ViewGroup container, int position,
                                    Object object) {
                ((ViewPager) container).removeView(pagerViews.get(position));
            }

            //每次滑动的时候生成的组件
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                if (pagerViews.get(position % pagerViews.size()).getParent() != null)
                    ((ViewPager) pagerViews.get(position % pagerViews.size()).getParent()).removeView(pagerViews.get(position % pagerViews.size()));
                try {
//					((ViewPager) container).addView(pagerViews.get(position));
                    ((ViewPager) container).addView(pagerViews.get(position % pagerViews.size()));
                } catch (Exception e) {
                    LoggerUtils.getLog(Ranking.class).error(e.getMessage());
                }
                return pagerViews.get(position);
            }
        });
        mViewPager.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        mViewPager.requestDisallowInterceptTouchEvent(true);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        mViewPager.requestDisallowInterceptTouchEvent(false);
                        break;
                }
                return false;
            }
        });
    }

}
